<template>
    <div class="about-us">
        <img class="logosize" src="@/assets/images/usercenter/user_logo1.png" alt="" />

        <div class="contact-cell">
            <div class="flexV">
                <img class="bbsize" src="@/assets/images/usercenter/user_bb.png" alt="">
                <span>检查版本更新：版本{{ versionCode }}</span>
            </div>
            <!-- <span v-if="versionInfo">现在已是最新版本</span> -->
            <el-button class="gx-button" @click="StartAtion">
                立即更新
            </el-button>
        </div>

        <div class="QrbgV">

            <div class="appQr">
                <img class="Qrimg" src="@/assets/images/login/login-qrcode.png" alt="">
                <span class="Qrtext">扫码下载移动端App</span>
            </div>
        </div>


        <!-- 编辑昵称弹窗 -->
        <el-dialog :append-to-body="true" v-model="visible" width="366" :before-close="handleClose"
            class="update-client-dialog" center>
            <div class="content">
                <h3>重启客户端</h3>
                <p>更新会重启客户端，同时关闭游戏并结算。</p>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="visible = false">以后再说</el-button>
                    <el-button type="primary" @click="updateVisible = true">立即更新</el-button>
                </span>
            </template>
        </el-dialog>


        <!-- 更新进度弹窗 -->
        <el-dialog :append-to-body="true" v-model="updateVisible" width="430" :before-close="updateHandleClose"
            :close-on-click-modal="false" :close-on-press-escape="false" class="update-client-dialog" center>
            <div class="content" style="text-align: center;">
                <img src="@/assets/images/usercenter/update_icon.png" alt="">
                <h3>{{ updateDetails.title || '版本更新' }}</h3>
                <p>版本号 {{ updateDetails.version || '1.0.1' }}</p>
                <div class="update-content">
                    <div class="item" v-for="(item, index) in updateContentList" :key="index">{{ index + 1 }}. {{ item
                    }}
                    </div>
                </div>
            </div>

            <div class="progress-container" style="margin-bottom: 15px;" v-if="updateIng">
                <div class="progress-info" style="padding-bottom: 5px;">
                    <span>正在更新</span>
                    <span>{{ percentage }}%</span>
                </div>
                <el-progress :percentage="percentage" :color="customColor" :show-text="false" />
            </div>

            <template #footer>
                <span class="dialog-footer" v-if="!updateIng">
                    <el-button @click="updateVisible = false">以后再说</el-button>
                    <el-button type="primary" @click="executeUpdate()">立即更新</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
defineOptions({
    name: 'AboutUs'
})
import { ref, onMounted, onUnmounted, computed } from 'vue'; // 添加 computed 导入
import { checkupdates } from '@/api/user';
import { getLocalStorageValue } from '@/utils/auth'

const versionInfo = ref({})
const visible = ref(false)
const updateVisible = ref(false)
const percentage = ref(0)
const customColor = ref('#ffe500')
const updateIng = ref(false)
const versionCode = ref('1.0.1')
const updateDetails = ref({
    version: '',
    title: '版本更新',
    description: '',
    forceUpdate: false
})

let messageHandler = null;

// 页面加载时获取初始数据
onMounted(async () => {
    getVersionCode();
    _checkupdates();

    // 添加 WebView 消息监听
    if (window.chrome && window.chrome.webview) {
        messageHandler = (event) => handleWebViewMessage(event);
        window.chrome.webview.addEventListener('message', messageHandler);
    }
});

// 组件卸载时移除事件监听
onUnmounted(() => {
    if (window.chrome && window.chrome.webview && messageHandler) {
        window.chrome.webview.removeEventListener('message', messageHandler);
    }
});

// 处理 WebView 发送的消息
const handleWebViewMessage = (event) => {
    console.log('Received message:', event.data);
    const data = event.data;

    if (data.type === 'updateInfo') {
        // 接收到更新信息
        updateDetails.value = {
            version: data.version,
            title: data.title || '版本更新',
            description: data.description || '',
            forceUpdate: data.forceUpdate || false
        };

        // 更新 hasUpdate 状态
        versionInfo.value = {
            hasUpdate: data.hasUpdate,
            ...data
        };

        // 如果有更新且是强制更新，直接显示更新对话框
        if (data.hasUpdate && data.forceUpdate) {
            updateVisible.value = true;
        }
    }
    else if (data.type === 'updateProgress') {
        // 更新进度信息
        updateIng.value = true;
        percentage.value = Math.round(data.percent);

        // 可以根据 phase 更新状态文本
        // data.phase 可能是 'downloading', 'extracting', 'installing'
    }
    else if (data.type === 'updateComplete') {
        // 更新完成
        percentage.value = 100;
        // 可以在这里添加更新完成后的处理逻辑
    }
    else if (data.type === 'updateError') {
        // 更新出错
        console.error('更新失败:', data.message);
        // 可以显示错误提示
    }
};

//壳子获取版本信息
const getVersionCode = async () => {
    const storedVersionCode = await getLocalStorageValue('versionCode')
    versionCode.value = storedVersionCode || '1.0.1';
    console.log('versionCode:', storedVersionCode)
};

//接口获取版本信息
const _checkupdates = async () => {
    const panamr = {};
    checkupdates(panamr).then((res) => {
        versionInfo.value = res.info
    }).catch((err) => {
        console.log(err);
    });
};

// 开始更新操作
const StartAtion = () => {
    if (window.chrome && window.chrome.webview) {
        window.chrome.webview.postMessage({ action: 'showUpdateWindow' });
    }
    // 请求检查更新
    // if (window.chrome && window.chrome.webview) {
    //     window.chrome.webview.postMessage({ action: 'checkForUpdates' });
    // }
    // // 显示更新对话框
    // updateVisible.value = true;
    // visible.value = false;
    // percentage.value = 0;
}

// 执行更新
const executeUpdate = () => {
    updateIng.value = true;
    if (window.chrome && window.chrome.webview) {
        window.chrome.webview.postMessage({ action: 'startUpdate' });
    }
}

// 关闭弹窗
const handleClose = () => {
    visible.value = false
}

// 更新弹窗关闭
const updateHandleClose = () => {
    // 如果不是强制更新才允许关闭
    if (!updateDetails.value.forceUpdate) {
        updateVisible.value = false;
        updateIng.value = false; // 重置更新状态
    }
}

// 延迟更新
const postponeUpdate = () => {
    if (window.chrome && window.chrome.webview) {
        window.chrome.webview.postMessage({ action: 'postponeUpdate' });
    }
    updateVisible.value = false;
    updateIng.value = false; // 重置更新状态
}

// 解析更新内容为列表
const updateContentList = computed(() => {
    if (updateDetails.value.description) {
        return updateDetails.value.description.split('\n').filter(item => item.trim() !== '');
    }
});
</script>


<style lang="scss" scoped>
.Qrtext {
    margin-top: 10px;
    color: #888888;
    font-size: 12px;
}

.Qrimg {
    width: 158px;
    height: 158px;

}

.QrbgV {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 80px;
}

.appQr {
    width: 190px;
    height: 213px;
    border: 1px solid #46484A;
    text-align: center;
    padding: 20px 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #141414;
    border-radius: 4px;
}

.gx-button {
    width: 80px;
    height: 34px;
    background: #FFE500;
    color: #121212;
    font-size: 14px;
    border: none;
}

.contact-cell {
    margin-top: 40px;
    background: #27292C;
    height: 64px;
    border-radius: 4px;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
    font-style: 'Bold';
    color: #888;
}

.flexV {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #e2e2e2;
}

.logosize {
    width: 228.48px;
    height: 52px;
}

.bbsize {
    width: 32px;
    height: 32px;
}

.about-us {
    background-color: #121517;
    color: #fff;
    box-sizing: border-box;
    padding: 20px;
    /* 使用flex布局实现底部固定 */
    display: flex;
    flex-direction: column;

}
</style>
<style lang="scss">
.update-client-dialog {
    .el-dialog__header {
        padding: 20px !important;

        .el-dialog__title {
            color: #fff;
        }
    }

    .el-dialog__body {
        padding: 0 40px;
        color: #888;

        h3 {
            font-size: 24px;
            font-weight: bold;
            color: #fff;
            margin-bottom: 10px;
        }

        p {
            font-size: 14px;
        }

        .update-content {
            padding: 30px 0;
            border-top: 1px solid #2e3033;
            text-align: left;

            .item {
                line-height: 32px;
                font-size: 14px;
            }
        }

        .progress-container {
            .progress-info {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }
    }
}
</style>
